/**
 * Created by wzh on 2016/5/18.
 */
var infos=[
    "basicInfo",
    "baseInfo",
    "businessInfo",
    "employeeInfo",
    "personalityInfo"
];
var repeatInfos=[
    "mobileNumberList",
    "emailList",
    "fixedNumberList",
    "addresss",
    "educationHistorys",
    "workHistorys",
    "familyInfos"
];
'use strict'
swan_pc
    .factory('Excel',function($window){
        var uri='data:application/vnd.ms-excel;base64,',
            template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64=function(s){return $window.btoa(unescape(encodeURIComponent(s)));},
            format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];})};
        return {
            tableToExcel:function(tableId,worksheetName){
                var table=$(tableId),
                    ctx={worksheet:worksheetName,table:table.html()},
                    href=uri+base64(format(template,ctx));
                return href;
            }
        };
    })
    .controller('ContactController',function($scope,ContactInfo,$rootScope,$state,$timeout,DateUtils,$filter,Upload,Excel,$q,ngDialog){
    $scope.contactBaseInfos = [];
    $scope.presentContactInfo;
    $scope.addContactInfo;
    $scope.dirty=[];

    //接口数据结构：在此处添加/删除变量，页面会自动做出修改

    //非循环变量的数据结构定义
    $scope.infoDateStruct= {
        basicInfo:[
            {
                name: "别名",
                key: "alias",
                image: "fa fa-font",
                show: 1,
                option:1
            },
            {
                name: "QQ",
                key: "qq",
                image: "fa fa-qq",
                show: 1,
                option:1
            },
            {
                name: "微信",
                key: "wechat",
                image: "fa fa-wechat",
                show: 1,
                option:1
            },
            {
                name: "生日",
                key: "birthDate",
                image: "fa fa-birthday-cake",
                show: 1,
                option:3
            }
        ],
        baseInfo: [
            {
                name: "英文名",
                key: "englishName",
                image: "fa fa-font",
                show: 1,
                option:1
            },
            {
                name:"swan号",
                key:"timing",
                image:"fa fa-clock-o",
                show:1,
                option:5
            },
            {
                name: "性别",
                key: "gender",
                image: "fa fa-comment",
                show: 1,
                option:4,
                radio:[
                    {
                        name:"女",
                        value:"0"
                    },
                    {
                        name:"男",
                        value:"1"
                    }
                ]
            },
            {
                name: "身高",
                key: "height",
                image: "fa fa-comment",
                show: 1,
                option:1
            },
            {
                name: "体重",
                key: "weight",
                image: "fa fa-comment",
                show: 1,
                option:1
            },
            {
                name: "血型",
                key: "blood",
                image: "fa fa-comment",
                show: 1,
                option:2,
                select:[
                    "A",
                    "B",
                    "O",
                    "AB"
                ]
            },
            {
                name: "民族",
                key: "ethnic",
                image: "fa fa-comment",
                show: 1,
                option:1
            },
            {
                name: "党派",
                key: "party",
                image: "fa fa-comment",
                show: 1,
                option:1
            },
            {
                name: "宗教",
                key: "religion",
                image: "fa fa-comment",
                show: 1,
                option:1
            },
            {
                name: "基本联系",
                key: "baseContact",
                image: "fa fa-comment",
                show: 1,
                option:1
            },
            {
                name: "芳邻圈",
                key: "isNeighbor",
                image: "fa fa-comment",
                show: 1,
                option:4,
                radio:[
                    {
                        name:"是",
                        value:true
                    },
                    {
                        name:"否",
                        value:false
                    }
                ]
            },
            {
                name: "照片URL",
                key: "photoUrl",
                image: "fa fa-font",
                show: 1,
                option:0
            }
        ],
        businessInfo:[
            {
                name: "业务关系",
                key: "businessConnection",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "业务类型",
                key: "businessConnectionKind",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "友好程度",
                key: "friendshipToOrg",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "地位",
                key: "positionInfo",
                image: "",
                show: 1,
                option:2,
                select:
                [
                    "普通员工",
                    "专业领导",
                    "高级经理",
                    "行政领导",
                    "总经理",
                    "最高领导"
                ]
            },
            {
                name: "对公司意义",
                key: "significanceToOrg",
                image: "",
                show: 1,
                option:1
            }
        ],
        employeeInfo:[
            {
                name: "部门",
                key: "department",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "汇报上级",
                key: "leaderName",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "级别",
                key: "level",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "职位",
                key: "position",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "工作专业类别",
                key: "professionsType",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "职责",
                key: "responsibility",
                image: "",
                show: 1,
                option:1
            }
        ],
        personalityInfo:[
            {
                name: "性格",
                key: "character1",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "商业联系",
                key: "businessConnection",
                image: "",
                show: 1,
                option:2,
                select:[
                    "客户",
                    "合作伙伴",
                    "竞争对手",
                    "供应商",
                    "其他"
                ]
            },
            {
                name: "星座",
                key: "constellation",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "友谊程度",
                key: "friendshipToMe",
                image: "",
                show: 1,
                option:2,
                select:[
                    "讨厌",
                    "烦",
                    "认识",
                    "接受",
                    "好感"
                ]
            },
            {
                name: "爱好",
                key: "hobby",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "重要程度",
                key: "importanceToMe",
                image: "",
                show: 1,
                option:2,
                select:[
                    "很重要",
                    "极其重要",
                    "重要",
                    "需要",
                    "不需要"
                ]
            },
            {
                name: "绰号",
                key: "nickName",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "私人关系",
                key: "personalConnection",
                image: "",
                show: 1,
                option:1
            },
            {
                name: "评论",
                key: "remark",
                image: "",
                show: 1,
                option:1
            }
        ]
    };
    //循环变量的数据结构定义
    $scope.repeatDateStruct={
        mobileNumberList: [
            {
                name: "",
                key: "name",
                image:"fa fa-phone",
                style:{
                    "width":"15%"
                },
                show:[],
                option:2,
                select:[
                    "默认",
                    "家庭",
                    "快捷",
                    "公司"
                ]
            },
            {
                name:"",
                key:"value",
                image:"",
                style:{
                    "width":"75%"
                },
                show:[],
                option:1
            }],
        emailList:[
            {
                name: "",
                key: "name",
                image:"fa fa-envelope",
                style:{
                    "width":"15%"
                },
                show:[],
                option:2,
                select:[
                    "默认",
                    "商用",
                    "公司"
                ]
            },
            {
                name:"",
                key:"value",
                image:"",
                style:{
                    "width":"75%"
                },
                show:[],
                option:1
            }],
        fixedNumberList: [
            {
                name: "",
                key: "name",
                image:"fa fa-phone",
                style:{
                    "width":"15%"
                },
                show:[],
                option:2,
                select:[
                    "默认",
                    "家庭",
                    "公司"
                ]
            },
            {
                name:"",
                key:"value",
                image:"",
                style:{
                    "width":"75%"
                },
                show:[],
                option:1
            }],
        addresss: [
            {
                name:"省",
                key:"province",
                show:[],
                option:1,
                preview:1,
                prename:"省"
            },
            {
                name:"市",
                key:"city",
                show:[],
                option:1,
                preview:1,
                prename:"市"
            },
            {
                name:"区/县/地级市",
                key:"district",
                show:[],
                option:1,
                preview:1,
                prename:"区/县/地级市"
            },
            {
                name:"区域",
                key:"area",
                show:[],
                option:1,
                preview:2,
                prename:""
            },
            {
                name:"详细地址",
                key:"detailAddress",
                show:[],
                option:1,
                preview:2,
                prename:""
            },
            {
                name:"邮政编码",
                key:"postcode",
                show:[],
                option:1,
                preview:3,
                prename:" 邮编"
            }
            /*
             "street": null,
             "area": null,
             "house": null,
             */
        ],
        educationHistorys: [
            {
                name:"学历",
                key:"diploma",
                show:[],
                option:1,
                preview:1,
                prename:":"
            },
            {
                name:"学校",
                key:"school",
                show:[],
                option:1,
                preview:1,
                prename:"("
            },
            {
                name:"入学日期",
                key:"entranceDate",
                show:[],
                option:3,
                preview:1,
                prename:"-"
            },
            {
                name:"毕业日期",
                key:"graduateDate",
                show:[],
                option:3,
                preview:1,
                prename:")"
            },
            {
                name:"学院",
                key:"institute",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"系",
                key:"faculty",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"主修",
                key:"major",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"班级",
                key:"schoolClass",
                show:[],
                option:1,
                preview:0
            }
        ],
        workHistorys: [
            {
                name:"公司名称",
                key:"company",
                show:[],
                option:1,
                preview:1,
                prename:"("
            },
            {
                name:"入职日期",
                key: "beginDate",
                show:[],
                option:3,
                preview:1,
                prename:"-"
            },
            {
                name:"离职日期",
                key:"endDate",
                show:[],
                option:3,
                preview:1,
                prename:")"
            },
            {
                name:"部门",
                key:"department",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"级别",
                key:"level",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"职位",
                key:"position",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"主攻领域",
                key:"professionsType",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"职责",
                key:"responsibility",
                show:[],
                option:1,
                preview:0
            },
            {
                name:"负责人",
                key:"reportPerson",
                show:[],
                option:1,
                preview:0
            }
        ],
        familyInfos:[
            {
                name:"关系",
                key:"relation",
                show:[],
                option:1,
                preview:1,
                prename:":"
            },
            {
                name:"姓名",
                key:"name",
                show:[],
                option:1,
                preview:2,
                prename:""
            },
            {
                name:"年龄",
                key:"age",
                show:[],
                option:1,
                preview:0,
                prename:""
            },
            {
                name:"教育背景",
                key:"educational",
                show:[],
                option:1,
                preview:0,
                prename:""
            },
            {
                name:"性别",
                key: "gender",
                show:[],
                option:4,
                preview:0,
                prename:"",
                radio:[
                    {
                        name:"女",
                        value:"0"
                    },
                    {
                        name:"男",
                        value:"1"
                    }
                ]
            },
            {
                name:"备注",
                key:"remark",
                show:[],
                option:1,
                preview:0,
                prename:""
            },
            {
                name:"工作单位",
                key:"workUnit",
                show:[],
                option:1,
                preview:0,
                prename:""
            }
        ]
    }

    //初始化按钮，模块的显示
    $scope.initAddressBox=function () {
        //button
        $scope.plus=true;
        $scope.check=true;
        $scope.chevronUp=false;
        $scope.chevronDown=false;
        $scope.chevronRight=false;
        $scope.chevronLeft=false;
        $scope.fresh=false;
        $scope.folder=false;
        $scope.addHint=false;
        //module
        $scope.detailContact=false;
    };
    $scope.initAddressBox();
    $scope.initAddContact=function(){
        $scope.plus=false;
        $scope.check=true;
        $scope.chevronUp=false;
        $scope.chevronDown=true;
        $scope.chevronRight=false;
        $scope.chevronLeft=false;
        $scope.fresh=true;
        $scope.folder=false;
        $scope.addHint=true;
    }
    //初始化ContactMore界面
    $scope.initContactMore=function () {
        $scope.plus = true;
        $scope.check = true;
        $scope.chevronUp = false;
        $scope.chevronDown = false;
        $scope.chevronRight = true;
        $scope.chevronLeft = false;
        $scope.fresh = true;
        $scope.folder=true;
        $scope.addHint=false;

        $scope.phoneDiv=true;
        $scope.emailDiv=true;
        $scope.fixDiv=true;
        $scope.businessDiv=true;
        $scope.employeeDiv=true;
        $scope.personalityDiv=true;
        $scope.addresssDiv=true;
        $scope.educationHistorysDiv=true;
        $scope.workHistorysDiv=true;
        $scope.familyInfosDiv=true;

        $scope.phoneDetail=true;
        $scope.emailDetail=true;
        $scope.fixDetail=true;
        $scope.businessDetail=true;
        $scope.employeeDetail=true;
        $scope.personalityDetail=true;
        $scope.addresssDetail=true;
        $scope.educationHistorysDetail=true;
        $scope.workHistorysDetail=true;
        $scope.familyInfosDetail=true;
    }
    $scope.initDirty=function(){
        $rootScope.contactDirty=false;
        $scope.dirty[0]=false;
        $scope.dirty[1]=false;
        $scope.dirty[2]=false;
        $scope.dirty[3]=false;
        $scope.dirty[4]=false;
        $scope.dirty[5]=false;
        $scope.dirty[6]=false;
        $scope.dirty[7]=false;
        $scope.dirty[8]=false;
        $scope.dirty[9]=false;
        $scope.dirty[10]=false;
        $scope.dirty[11]=false;
        $scope.dirty[12]=false;
        $scope.dirty[13]=false;
    }

    //第一部分：页面显示/隐藏部分

    //显示 个人信息图标（性别，邻居关系）
    $scope.disPersonalMessage=function (option){
        do{
            if ($scope.presentContactInfo==undefined||$scope.presentContactInfo.baseInfo==undefined) break;
            if (option==0&&($scope.presentContactInfo.baseInfo.isNeighbor==undefined||$scope.presentContactInfo.baseInfo.isNeighbor.toString()!="true")) break;
            if ($scope.presentContactInfo.baseInfo.gender!=0&&$scope.presentContactInfo.baseInfo.gender!=1) break;
            if (option==1&&$scope.presentContactInfo.baseInfo.gender==0) break;
            if (option==2&&$scope.presentContactInfo.baseInfo.gender==1) break;
            return true;
        }while (0);
        return false;
    };
    //显示详细信息 option=1 显示；option=2 隐藏 option=3 显示 option=4 隐藏
    $scope.display=function(option){
        if (option==1){
            $scope.chevronUp=true;
            $scope.chevronDown=false;
            $scope.detailContact=true;
        }
        else if(option==2){
            $scope.chevronUp=false;
            $scope.chevronDown=true;
            $scope.detailContact=false;
        }
        else if(option==3){
            $scope.chevronLeft=false;
            $scope.chevronRight=true;
        }
        else if(option==4){
            if($scope.phoneDiv&& $scope.emailDiv&&$scope.fixDiv&&$scope.businessDiv&&$scope.employeeDiv&&$scope.personalityDiv&& $scope.addresssDiv&&$scope.educationHistorysDiv&&$scope.workHistorysDiv&&$scope.familyInfosDiv){
                alert("没有模块被隐藏，无需折叠");
                return;
            }
            $scope.chevronLeft=true;
            $scope.chevronRight=false;
        }
    }
    //显示和输入框的切换
    $scope.getTittleFocus=function() {
        $timeout(function() {
                document.getElementById('showTitleName').focus();
            }
        );
    }
    //获取class名称 用于给模块赋class属性，进而获取dom节点实现聚焦
    $scope.getClassName=function(block,$index1,$index2){
        //输入：block 区块 index1 区内偏移块 index2
        if ($index2==undefined) return infos[block].toString()+$index1+"DetailInput";
        else return repeatInfos[block]+$index1+"offset"+$index2+"DetailInput";
    }
    //非repeat框的切换
    $scope.ngShowOrInput=function(block,index,option){
        /*
         * 输入：block：要双击显示input框的区块 类型为数字
         *       index：该input在该block中的序号
         *       option：选项，为2/3表示检查是否显示，为0/1为赋值
         * 其他功能: option=0表示要显示输入框 还会为该输入框聚焦
         */
        if (option==2) return $scope.infoDateStruct[infos[block]][index].show==1?true:false;
        else if (option==3) return $scope.infoDateStruct[infos[block]][index].show==1?false:true;
        else {

            $scope.infoDateStruct[infos[block]][index].show=option;
            if(option==0&&$scope.infoDateStruct[infos[block]][index].option==1) {
                var x=$scope.getClassName(block,index);
                var y=document.getElementsByClassName(x);

                $timeout(function (){
                    y.item(0).focus();
                });
            }
        }
    };
    //repeat类型框的切换
    $scope.repeatShowOrInput=function(block,offset,index,option){
        /*
         * 输入：block：要双击显示input框的区块 类型为数字
         *       offset: 该数据的条目
         *       index：该input在该offset中的序号
         *       option：选项，为2/3表示检查是否显示，为0/1为赋值
         * 其他功能: option=0表示要显示输入框 还会为该输入框聚焦
         */
        if (option==2) return $scope.repeatDateStruct[repeatInfos[block]][index].show[offset]==1?true:false;
        else if (option==3) return $scope.repeatDateStruct[repeatInfos[block]][index].show[offset]==1?false:true;
        else {

            $scope.repeatDateStruct[repeatInfos[block]][index].show[offset]=option;
            if(option==0&&$scope.repeatDateStruct[repeatInfos[block]][index].option==1) {
                var x=$scope.getClassName(block,offset,index)
                var y=document.getElementsByClassName(x);

                $timeout(function (){
                    y.item(0).focus();
                });
            }
        }
    };
    //contactMore所有标签折叠
    $scope.hideAllDetail=function(){
        if (($scope.phoneDiv|| $scope.emailDiv||$scope.fixDiv||$scope.businessDiv||$scope.employeeDiv||$scope.personalityDiv|| $scope.addresssDiv||$scope.educationHistorysDiv||$scope.workHistorysDiv||$scope.familyInfosDiv)==false){
            $scope.phoneDiv=true;
            $scope.emailDiv=true;
            $scope.fixDiv=true;
            $scope.businessDiv=true;
            $scope.employeeDiv=true;
            $scope.personalityDiv=true;
            $scope.addresssDiv=true;
            $scope.educationHistorysDiv=true;
            $scope.workHistorysDiv=true;
            $scope.familyInfosDiv=true;
        }
        else if (($scope.phoneDetail&&$scope.phoneDiv|| $scope.emailDetail&&$scope.emailDiv||$scope.fixDetail&&$scope.fixDiv||$scope.businessDetail&&$scope.businessDiv||$scope.employeeDetail&&$scope.employeeDiv||$scope.personalityDetail&&$scope.personalityDiv|| $scope.addresssDetail&&$scope.addresssDiv||$scope.educationHistorysDetail&&$scope.educationHistorysDiv||$scope.workHistorysDetail&&$scope.workHistorysDiv||$scope.familyInfosDetail&&$scope.familyInfosDiv)==false){
            if($scope.phoneDiv) $scope.phoneDetail=true;
            if($scope.emailDiv) $scope.emailDetail=true;
            if($scope.fixDiv) $scope.fixDetail=true;
            if($scope.businessDiv) $scope.businessDetail=true;
            if($scope.employeeDiv) $scope.employeeDetail=true;
            if($scope.personalityDiv) $scope.personalityDetail=true;
            if($scope.addresssDiv) $scope.addresssDetail=true;
            if($scope.educationHistorysDiv) $scope.educationHistorysDetail=true;
            if($scope.workHistorysDiv) $scope.workHistorysDetail=true;
            if($scope.familyInfosDiv) $scope.familyInfosDetail=true;
        }
        else {
            if($scope.phoneDiv) $scope.phoneDetail=false;
            if($scope.emailDiv) $scope.emailDetail=false;
            if($scope.fixDiv) $scope.fixDetail=false;
            if($scope.businessDiv) $scope.businessDetail=false;
            if($scope.employeeDiv) $scope.employeeDetail=false;
            if($scope.personalityDiv) $scope.personalityDetail=false;
            if($scope.addresssDiv) $scope.addresssDetail=false;
            if($scope.educationHistorysDiv) $scope.educationHistorysDetail=false;
            if($scope.workHistorysDiv) $scope.workHistorysDetail=false;
            if($scope.familyInfosDiv) $scope.familyInfosDetail=false;
        }
    }
    //repeat模块中增加节点 输入 模块号
    $scope.add=function(block){
        if (block==0) $scope.presentContactInfo.baseInfo.mobileNumberList.push({});
        else if (block==1) $scope.presentContactInfo.baseInfo.emailList.push({});
        else if (block==2) $scope.presentContactInfo.baseInfo.fixedNumberList.push({});
        else if (block==3) $scope.presentContactInfo.baseInfo.addresss.push({});
        else if (block==4) $scope.presentContactInfo.educationHistorys.push({});
        else if (block==5) $scope.presentContactInfo.workHistorys.push({});
        else if (block==6) $scope.presentContactInfo.familyInfos.push({});
    }
    //repeat模块中删除节点 输入 模块号
    $scope.del=function(block,position){
        if (block==0) position==undefined?$scope.presentContactInfo.baseInfo.mobileNumberList.pop():$scope.presentContactInfo.baseInfo.mobileNumberList.splice(position,1);
        else if (block==1) position==undefined?$scope.presentContactInfo.baseInfo.emailList.pop():$scope.presentContactInfo.baseInfo.emailList.splice(position,1);
        else if (block==2) position==undefined?$scope.presentContactInfo.baseInfo.fixedNumberList.pop():$scope.presentContactInfo.baseInfo.fixedNumberList.splice(position,1);
        else if (block==3) position==undefined?$scope.presentContactInfo.baseInfo.addresss.pop():$scope.presentContactInfo.baseInfo.addresss.splice(position,1);
        else if (block==4) position==undefined?$scope.presentContactInfo.educationHistorys.pop():$scope.presentContactInfo.educationHistorys.splice(position,1);
        else if (block==5) position==undefined?$scope.presentContactInfo.workHistorys.pop():$scope.presentContactInfo.workHistorys.splice(position,1);
        else if (block==6) position==undefined?$scope.presentContactInfo.familyInfos.pop():$scope.presentContactInfo.familyInfos.splice(position,1);
    }
    //修改日期格式 option=0变为格林尼治时间 option=1变为普通时间
    $scope.tempDate=new Date("1900", "01", "01");
    $scope.changeDate=function(model,block,index,key,option) {
        $scope.presentContactInfoIndex = [
            [
                $scope.presentContactInfo.baseInfo,
                $scope.presentContactInfo.baseInfo,
                $scope.presentContactInfo.businessInfo,
                $scope.presentContactInfo.employeeInfo,
                $scope.presentContactInfo.personalityInfo
            ],
            [
                $scope.presentContactInfo.baseInfo.mobileNumberList,
                $scope.presentContactInfo.baseInfo.emailList,
                $scope.presentContactInfo.baseInfo.fixedNumberList,
                $scope.presentContactInfo.baseInfo.addresss,
                $scope.presentContactInfo.educationHistorys,
                $scope.presentContactInfo.workHistorys,
                $scope.presentContactInfo.familyInfos
            ]
        ];
        //alert("m:"+model+" b:"+block+" i:"+index+" k:"+key+" "+" o:"+option);
        if (index == -1) {
            if (option==0) {
                if(typeof($scope.presentContactInfoIndex[model][block][key])!="string") return;
                $scope.tempDate = DateUtils.convertLocaleDateFromServer($scope.presentContactInfoIndex[model][block][key]);
            }
            else $scope.presentContactInfoIndex[model][block][key] = DateUtils.convertLocaleDateToServer($scope.tempDate);
        }
        else {
            if (option==0){
                if(typeof($scope.presentContactInfoIndex[model][block][index][key])!="string") return;
                $scope.tempDate=DateUtils.convertLocaleDateFromServer($scope.presentContactInfoIndex[model][block][index][key]);
            }
            else $scope.presentContactInfoIndex[model][block][index][key] = DateUtils.convertLocaleDateToServer($scope.tempDate);
        }
    }
    //获取每个节点之前的图标（如果有）
    $scope.ngGetBaseInfoImage=function(block,index){
        return $scope.infoDateStruct[infos[block]][index].image;
    };
    //获取每个节点之前的图标（如果有）
    $scope.ngRepeatGetBaseInfoImage=function(block,index){
        //alert("hello wzh:"+block+" and index:"+index);
        return $scope.repeatDateStruct[repeatInfos[block]][index].image;
    };
    //获取每个radio按钮对应的值用于显示
    $scope.getRadioName=function(block,offset,index,key){
        if($scope.presentContactInfoIndex==undefined) return "";
        if (offset==-1) {
            var value=$scope.presentContactInfoIndex[0][block][key];
            if (value==undefined) return "未设置";
            for (var i=0;i<$scope.infoDateStruct[infos[block]][index].radio.length;i=i+1){
                if ($scope.infoDateStruct[infos[block]][index].radio[i].value.toString()==value.toString()) return $scope.infoDateStruct[infos[block]][index].radio[i].name;
            }
            return "未设置";
        }
        else {
            var value=$scope.presentContactInfoIndex[1][block][offset][key];
            if (value==undefined) return "未设置";
            for (var i=0;i<$scope.repeatDateStruct[repeatInfos[block]][index].radio.length;i=i+1){
                if ($scope.repeatDateStruct[repeatInfos[block]][index].radio[i].value.toString()==value.toString()) return $scope.repeatDateStruct[repeatInfos[block]][index].radio[i].name;
            }
            return "未设置";
        }
    }

    //第二部分 功能模块组织

    //对联系人进行排序
    //比较函数 根据选项对2个字符串进行比较
    $scope.compare=function(str1,str2){
        return str1.localeCompare(str2);
    }

    //对联系人进行筛选
    //用于使用姓名/电话进行筛选的筛选信息
    $scope.filterInfo="";
    //用于提供更多筛选的筛选信息
        $scope.filterInfos= {
            name: "",
            one: {
                a: false,
                b: false,
                c: false,
                d: false,
                e: false
            },
            two: {
                a: false,
                b: false,
                c: false,
                d: false,
                e: false
            },
            three: {
                a: false,
                b: false,
                c: false,
                d: false,
                e: false
            }
        }
    //筛选函数，用于对联系人列表进行筛选
    $scope.infosFilter=function(item){
        if (item.baseInfo.name.indexOf($scope.filterInfos.name) < 0) return false;
        if (!(!$scope.filterInfos.one.a && !$scope.filterInfos.one.b && !$scope.filterInfos.one.c && !$scope.filterInfos.one.d && !$scope.filterInfos.one.e
            || item.personalityInfo != undefined && (
            $scope.filterInfos.one.a && item.personalityInfo.businessConnection == "客户" ||
            $scope.filterInfos.one.b && item.personalityInfo.businessConnection == "合作伙伴" ||
            $scope.filterInfos.one.c && item.personalityInfo.businessConnection == "竞争对手" ||
            $scope.filterInfos.one.d && item.personalityInfo.businessConnection == "供应商" ||
            $scope.filterInfos.one.e && item.personalityInfo.businessConnection == "其他"))) return false;
        if (!(!$scope.filterInfos.two.a && !$scope.filterInfos.two.b && !$scope.filterInfos.two.c && !$scope.filterInfos.two.d && !$scope.filterInfos.two.e
            || item.personalityInfo != undefined && (
            $scope.filterInfos.two.a && item.personalityInfo.importanceToMe == "不需要" ||
            $scope.filterInfos.two.b && item.personalityInfo.importanceToMe == "需要" ||
            $scope.filterInfos.two.c && item.personalityInfo.importanceToMe == "重要" ||
            $scope.filterInfos.two.d && item.personalityInfo.importanceToMe == "很重要" ||
            $scope.filterInfos.two.e && item.personalityInfo.importanceToMe == "极其重要"))) return false;
        if (!(!$scope.filterInfos.three.a && !$scope.filterInfos.three.b && !$scope.filterInfos.three.c && !$scope.filterInfos.three.d && !$scope.filterInfos.three.e
            || item.personalityInfo != undefined && (
            $scope.filterInfos.three.a && item.personalityInfo.friendshipWithMe == "讨厌" ||
            $scope.filterInfos.three.b && item.personalityInfo.friendshipWithMe == "烦" ||
            $scope.filterInfos.three.c && item.personalityInfo.friendshipWithMe == "认识" ||
            $scope.filterInfos.three.d && item.personalityInfo.friendshipWithMe == "接受" ||
            $scope.filterInfos.three.e && item.personalityInfo.friendshipWithMe == "好感"))) return false;
        return true;
    }
    //对联系人进行排序
    $scope.sort=function(contactArr){
        for (var i=0;i<contactArr.length-1;i++){
            var temp=i;
            for (var j=i+1;j<contactArr.length;j++){
                if ($scope.compare(contactArr[temp].baseInfo.name,contactArr[j].baseInfo.name)>0) temp=j;
            }
            if (temp!=i){
                var temporary=contactArr[temp];
                contactArr[temp]=contactArr[i];
                contactArr[i]=temporary;
            }
        }
    }
    //显示联系人的重要性
    $scope.getImportance=function(personalityInfo){
        var option=0;
        if(personalityInfo==undefined) option=0;
        else {
            if (personalityInfo.importanceToMe == "很重要") option += 1;
            if (personalityInfo.friendshipToMe == "好感") option += 2;
        }
        return option==3?{"color":"red"}:option==2?{"color":"green"}:option==1?{"color":"blue"}:{};
    }
    $scope.getImportanceTip=function(personalityInfo){
        var temp="";
        if(personalityInfo==undefined) return "";
        else {
            if (personalityInfo.importanceToMe == "很重要") temp += " 很重要";
            if (personalityInfo.friendshipToMe == "好感") temp += " 有好感";
        }
        return temp;
    }
    //更新当前显示的联系人详细信息
    $scope.updatePresentContact=function (id){
        ContactInfo.queryAll({infoid:id},function(result){
            $scope.presentContactInfo=result;
            $scope.presentContactInfoIndex = [
                [
                    $scope.presentContactInfo.baseInfo,
                    $scope.presentContactInfo.baseInfo,
                    $scope.presentContactInfo.businessInfo,
                    $scope.presentContactInfo.employeeInfo,
                    $scope.presentContactInfo.personalityInfo
                ],
                [
                    $scope.presentContactInfo.baseInfo.mobileNumberList,
                    $scope.presentContactInfo.baseInfo.emailList,
                    $scope.presentContactInfo.baseInfo.fixedNumberList,
                    $scope.presentContactInfo.baseInfo.addresss,
                    $scope.presentContactInfo.educationHistorys,
                    $scope.presentContactInfo.workHistorys,
                    $scope.presentContactInfo.familyInfos
                ]
            ];
        });
    };
    //加载用户联系人列表
    $scope.loadAll = function(option) {
        $scope.opt=option;
        ContactInfo.query({page:0, size: 3000, sort: ['id' + ',' + 'asc', 'id']},function(result) {
            $scope.contactBaseInfos = result;
            if ($scope.contactBaseInfos.length==0&&$rootScope.toState.name!="addcontact"&&$rootScope.toState.name!="companyaddcontact") $state.go("contacthint");
            else if($rootScope.toState.name=="contacthint") {
                $state.go("contactdetail");
            }
            else {
                $scope.sort($scope.contactBaseInfos);
                if ($scope.opt == undefined) {
                    if ($scope.contactInCompanyId!=undefined&&$scope.contactInCompanyId>=0)
                        $scope.updatePresentContact($scope.contactInCompanyId);
                    else
                        $scope.updatePresentContact($scope.contactBaseInfos[0].id);
                }
                else if ($scope.opt==2) return;
                else {
                    $scope.initDirty();
                    $scope.updatePresentContact($scope.presentContactInfo.id);
                }
            }
        });
    };
    //清空新建联系人的数据结构
    $scope.clear = function () {
        $scope.addContactInfo={
            "baseInfo": {
                "addresss": [
                    {
                        "area": null,
                        "city": null,
                        "district": null,
                        "house": null,
                        "postcode": null,
                        "province": null,
                        "street": null
                    }
                ],
                "alias": null,
                "baseContact": null,
                "birthDate": null,
                "blood": null,
                "emailList": [
                    {
                        "name": "",
                        "value": ""
                    }
                ],
                "englishName": null,
                "ethnic": null,
                "fixedNumberList": [
                    {
                        "name": "",
                        "value": ""
                    }
                ],
                "gender": 1,
                "height": null,
                //"id": 0,
                "isNeighbor": false,
                "mobileNumberList": [
                    {
                        "name": "",
                        "value": ""
                    }
                ],
                "name": null,
                "party": null,
                "photoUrl": null,
                "qq": null,
                "religion": null,
                "timing": null,
                "wechat": null,
                "weight": null
            },
            "businessInfo": {
                "businessConnection": null,
                "businessConnectionKind": null,
                "friendshipToOrg": null,
                "positionInfo": null,
                "significanceToOrg": null
            },
            "educationHistorys": [
                {
                    "diploma": null,
                    "entranceDate": null,
                    "faculty": null,
                    "graduateDate": null,
                    "institute": null,
                    "major": null,
                    "school": null,
                    "schoolClass": null,
                }
            ],
            "employeeInfo": {
                "department": null,
                "leaderName": null,
                "level": null,
                "position": null,
                "professionsType": null,
                "responsibility": null
            },
            "familyInfos": [
                {
                    "age": null,
                    "educational": null,
                    "evaluation": null,
                    "gender": 0,
                    "name": null,
                    "relation": null,
                    "remark": null,
                    "workUnit": null
                }
            ],
            "personalityInfo": {
                "businessConnection": null,
                "character1": null,
                "constellation": null,
                "friendshipToMe": null,
                "hobby": null,
                "importanceToMe": null,
                "isNeighbor": false,
                "nickName": null,
                "personalConnection": null,
                "remark": null
            },
            "revision": 0,
            "tag": null,
            "userCompanyName": null,
            "workHistorys": [
                {
                    "beginDate": null,
                    "company": null,
                    "department": null,
                    "endDate": null,
                    "level": null,
                    "position": null,
                    "professionsType": null,
                    "reportPerson": null,
                    "responsibility": null,
                }
            ]
        }
    };
    //刷新整个联系人页面
    $scope.refresh = function (option) {
        if ($rootScope.toState.name=="companyaddcontact") $scope.initAddContact();
        if(option==2) option=1;
        else if($rootScope.contactDirty) {
            if(!confirm("有数据未提交，确定要重置么?")) return;
        }
        $scope.loadAll(option);
        $scope.clear();
    };
    if($rootScope.toState!="companyaddcontact") $scope.refresh();
    //返回到联系人详细列表
    $scope.back=function(){
        if($rootScope.contactDirty) {
            if(!confirm("有数据未提交，确定要返回么?")) return;
        }
        $scope.loadAll(1);
        //恢复下拉菜单
        $scope.display(2);
        if($rootScope.toState.name=="companycontactdetail") $state.go("companycontact");
        else $state.go("contactdetail");
    };

    //第三部分：交互逻辑部分

    //添加新的联系人基本信息的方法
    $scope.addBase=function(){
        if($rootScope.contactDirty) {
            if(!confirm("有数据未提交，确定要放弃修改并新建联系人么?")) return;
        }
        $scope.initDirty();
        $scope.display(2);
        $state.go("addcontact");
    };
    //点击事件，切换联系人的基本信息到当前选中的联系人
    $scope.changedetail= function (id){
        if ($scope.presentContactInfo.id==id) return;
        if($rootScope.contactDirty) {
            if(!confirm("有数据未提交，确定要放弃修改并切换联系人么?")) return;
        }
        $scope.updatePresentContact(id);
        $state.go("contactdetail");
        $scope.initDirty();
    };
    //新建/更新联系人
    var onSaveSuccess = function (result) {
        $scope.refresh(2);
        if($rootScope.toState.name=="addcontact") {
            $scope.updatePresentContact(result.id);
        }
        alert("保存成功");
        $scope.initDirty();
        if($rootScope.toState.name=="companyaddcontact") $state.go("companycontact");
        else if($rootScope.toState.name!="contactmore"&&$rootScope.toState.name!='companycontactdetail') $state.go("contactdetail");
    };
    var onSaveError = function (result) {
        alert("保存失败");
    };
    $scope.saveInfo=function(){
        //if(!confirm("确定数据无误，要提交么")) return;
        if($rootScope.toState.name=="contactdetail"||$rootScope.toState.name=="contactmore"||$rootScope.toState.name=="companycontactdetail"){
            ContactInfo.update({},$scope.presentContactInfo, onSaveSuccess, onSaveError);
        }
        else if($rootScope.toState.name=="addcontact"||$rootScope.toState.name=="companyaddcontact"){
            if ($rootScope.toState.name=="companyaddcontact") $scope.addContactInfo.userCompanyName=$scope.presentCompanyInfo.companyBaseInfo.name;
            ContactInfo.save({},$scope.addContactInfo, onSaveSuccess, onSaveError);
        }
        else{
            alert("请先创建一个联系人再进行修改提交操作");
        }
    };
    //删除联系人
    var freshOption;
    var onDeleteSuccess = function (result) {
        $scope.loadAll(freshOption);
        alert("删除成功");
    };
    var onDeleteError = function (result) {
        alert(result.message);
    };
    $scope.checkDeleteAbleById=function(id){
        var able=true;
        _.forEach($scope.contactBaseInfos,function(item){
            if (item.id==id&&item.baseInfo.timing!=undefined&&item.baseInfo.timing!="") able=false
        })
        return able;
    }
    $scope.delete=function(id){
        if(!$scope.checkDeleteAbleById(id)) {
            alert("请先解除好友关系在删除联系人")
            return;
        }
        if(!confirm("确定要删除么")) return;
        if(id==$scope.presentContactInfo.id) freshOption=undefined;
        else freshOption=2;
        ContactInfo.delete({infoid:id}, onDeleteSuccess, onDeleteError);
    }
    //修改检查
    $scope.dirtySet=function(index){
        $rootScope.contactDirty=true;
        $scope.dirty[index]=true;
    }

    //照片上传部分:
        $scope.file={
            photo:undefined
        };
        $scope.submit = function() {
            if ($scope.file.photo!=undefined) {
                $scope.upload($scope.file.photo);
            }
        };
        $scope.upload = function (file) {
            Upload.upload({
                url: '/api/uploadFile',
                data: {file: file}
            }).then(function (resp) {
                var location="http://www.diamondtiming.com:8080";
                $scope.presentContactInfo.baseInfo.photoUrl=location+resp.data.path;
                ContactInfo.update({},$scope.presentContactInfo,function (result) {
                    $scope.loadAll(1);
                })
                $scope.file.photo=undefined;
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });
        };
        //yinyong
        function datenum(v, date1904) {
            if (date1904) {
                v += 1462;
            }
            var epoch = Date.parse(v);
            return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
        }
        //yinyong
        function sheet_from_array_of_arrays(data) {
            var ws = {};
            var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
            for (var R = 0; R !== data.length; ++R) {
                for (var C = 0; C !== data[R].length; ++C) {
                    if (range.s.r > R) {
                        range.s.r = R;
                    }
                    if (range.s.c > C) {
                        range.s.c = C;
                    }
                    if (range.e.r < R) {
                        range.e.r = R;
                    }
                    if (range.e.c < C) {
                        range.e.c = C;
                    }
                    var cell = {v: data[R][C]};
                    if (cell.v === null) {
                        continue;
                    }
                    var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

                    if (typeof cell.v === 'number') {
                        cell.t = 'n';
                    } else if (typeof cell.v === 'boolean') {
                        cell.t = 'b';
                    } else if (cell.v instanceof Date) {
                        cell.t = 'n';
                        cell.z = XLSX.SSF._table[14];
                        cell.v = datenum(cell.v);
                    }
                    else {
                        cell.t = 's';
                    }

                    ws[cell_ref] = cell;
                }
            }
            if (range.s.c < 10000000) {
                ws['!ref'] = XLSX.utils.encode_range(range);
            }
            return ws;
        }
        //yinyong
        function Workbook() {
            if (!(this instanceof Workbook)) {
                return new Workbook();
            }
            this.SheetNames = [];
            this.Sheets = {};
        }
        $scope.downExcel = function () {
            var d=$q.defer();
            var p=d.promise;
            var t=[];
            var f=0;
            for(var i=0;i<$scope.contactBaseInfos.length;i++){
                ContactInfo.queryAll({infoid:$scope.contactBaseInfos[i].id},function(result){
                    t.push(result);
                    f++;
                    if (f==$scope.contactBaseInfos.length) d.resolve(t);
                },function (result) {
                    d.reject("网络连接错误")
                })
            }
            p.then(function(t){
                createExcel(t, '联系人.xlsx')
            },function(r){
                alert("导出失败:"+r);
            });
        };
        function getHead() {
            var h=[];
            h.push("姓名");
            h.push("标签");
            h.push("公司");
            var k = Object.keys($scope.infoDateStruct);
            for (var i=0;i<k.length;i++){
                var b=$scope.infoDateStruct[k[i]];
                for (x in b){
                    h.push(b[x].name);
                }
            }
            k = Object.keys($scope.repeatDateStruct);
            for (var i=0;i<k.length;i++){
                var b=$scope.repeatDateStruct[k[i]];
                for (x in b){
                    var n=b[x].name!=""?b[x].name:x==0?(i==0?"移动电话类型":i==1?"电子邮箱类型":"固定电话类型"):i==0?"移动电话":i==1?"电子邮箱":"固定电话";
                    h.push(n);
                }
            }
            return h;
        }
        function getBody(d) {
            var r=[];
            r.push(d.baseInfo.name);
            r.push(d.tag);
            r.push(d.userCompanyName);
            var k=Object.keys($scope.infoDateStruct);
            for (var i=0;i<k.length;i++){
                var t=$scope.infoDateStruct[k[i]];
                for (x in t){
                    name=k[i]!="basicInfo"?k[i]:"baseInfo";
                    if (d[name]==undefined) r.push("")
                    else r.push(d[name][t[x].key]);
                }
            }
            var k=Object.keys($scope.repeatDateStruct);
            for (var i=0;i<k.length;i++){
                var t=$scope.repeatDateStruct[k[i]];
                for (x in t){
                    var m;
                    if(i<4){
                        if (d["baseInfo"][k[i]]==undefined) m=[];
                        else m=d["baseInfo"][k[i]];
                    }
                    else{
                        if (d[k[i]]==undefined) m=[];
                        else m=d[k[i]];
                    }
                    var s="";
                    for (p in m){
                        if(p!=0) s+="\n";
                        s+=m[p][t[x].key];
                    }
                    r.push(s);
                }
            }
            return r;
        }
        function createExcel(data, file_path) {
            var head=getHead();
            var body=[];
            for (x in data){
                body.push(getBody(data[x]));
            }
                //headKey.push(column.name);
            /*body = _.map(data, function (d) {
                return headKey.map(function (key) {
                    var a = key.lastIndexOf('['), b = key.lastIndexOf(']');

                    if (key.lastIndexOf('[') != -1) {
                        var arrKey = key.substring(0, a);
                        var fieldKey = key.substring(b + 2, key.length);
                        var arr = _.get(d, arrKey);
                        if (!_.isArray(arr))return null;
                        return _.map(arr, fieldKey).join('\n')
                    }
                    return _.get(d, key);
                })
            });*/
            var array = [head,].concat(body);
            var wb = new Workbook(), ws = sheet_from_array_of_arrays(array);

            /* add ranges to worksheet */
            // ws['!merges'] = ranges;
            var ws_name = "Sheet";
            /* add worksheet to workbook */
            wb.SheetNames.push(ws_name);
            wb.Sheets[ws_name] = ws;

//         var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
            // var buffer = new Buffer(wbout, 'binary');
            // fs.writeFileSync(file_path, buffer);
            /* bookType can be 'xlsx' or 'xlsm' or 'xlsb' */
            var wopts = {bookType: 'xlsx', bookSST: true, type: 'binary'};

            var wbout = XLSX.write(wb, wopts);

            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }

            /* the saveAs call downloads a file on the local machine */
            saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), file_path)
        }
        function sheet_to_data(workbook) {
            var result = null;
            workbook.SheetNames.forEach(function (sheetName) {
                var json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1, raw: true});
                if (!_.isArray(json) || json.length < 2)return;
                $scope.head = json[0];
                $scope.body = json.slice(1);
                if (_.xor(getHead(),$scope.head).length>0) {
                    alert("文件头部错误");
                    return false;
                };
                console.log($scope.body)
                ngDialog.open({
                    templateUrl:"scripts/components/myself/contact/uploadContactDialog/uploadContactDialog.html",
                    scope:$scope,
                    controller:["$scope",function($scope){
                        var df=$q.defer();
                        var pm=df.promise;
                        $scope.solved=0;
                        $scope.check=new Array($scope.body.length);
                        $scope.exist=new Array($scope.body.length);
                        $scope.checkExist=function () {
                            for (var i in $scope.body){
                                for (var y=0;y<$scope.contactBaseInfos.length;y++){
                                    if ($scope.body[i][0]==$scope.contactBaseInfos[y].baseInfo.name) $scope.exist[i]=true;
                                }
                            }
                        }
                        $scope.checkExist();
                        $scope.length=0;
                        $scope.pushOrPop=function($index) {
                            if($scope.check[$index]==1){
                                $scope.length++;
                            }
                            else $scope.length--;
                        }
                        $scope.checkAll=function (){
                            for (var i=0;i<$scope.check.length;i++){
                                $scope.check[i]=1;
                            }
                            $scope.length=$scope.check.length;
                        }
                        $scope.unCheckAll=function (){
                            for (var i=0;i<$scope.check.length;i++){
                                $scope.check[i]=0;
                            }
                            $scope.length=0;
                        }
                        $scope.reCheckAll=function(){
                            for (var i=0;i<$scope.check.length;i++){
                                $scope.check[i] = $scope.check[i] ==1?0:1;
                            }
                            $scope.length=$scope.check.length-$scope.length
                        }
                        $scope.checkAllUnexist=function(){
                            for (var i=0;i<$scope.check.length;i++){
                                if(!$scope.exist[i]) {
                                    if ($scope.check[i] != 1) {
                                        $scope.check[i] = 1;
                                        $scope.length++;
                                    }
                                }
                            }
                        }
                        $scope.uploadDate=function(b){
                            $scope.clear();
                            var a=$scope.addContactInfo;
                            var p=0;
                            a.baseInfo.name=b[p++]!="null"?b[p-1]:undefined;
                            a.tag=b[p++]!="null"?b[p-1]:undefined;
                            a.userCompanyName=b[p++]!="null"?b[p-1]:undefined;
                            var k=Object.keys($scope.infoDateStruct);
                            for (var i=0;i<k.length;i++){
                                var t=$scope.infoDateStruct[k[i]];
                                for (x in t){
                                    name=k[i]!="basicInfo"?k[i]:"baseInfo";
                                    a[name][t[x].key]=b[p++]!="null"?b[p-1]:undefined;
                                }
                            }
                            var k=Object.keys($scope.repeatDateStruct);
                            for (var i=0;i<k.length;i++){
                                var t=$scope.repeatDateStruct[k[i]];
                                for (x in t){
                                    var c=b[p++];
                                    c=c==undefined?"":c;
                                    var m=c.split("\n");
                                    for (var l in m){
                                        if(i<4) {
                                            if(x==0) a["baseInfo"][k[i]][l]={};
                                            a["baseInfo"][k[i]][l][t[x].key] = m[l]!="null"?m[l]:undefined;
                                        }
                                        else {
                                            if(x==0) a[k[i]][l]={};
                                            a[k[i]][l][t[x].key]= m[l]!="null"?m[l]:undefined;
                                        }
                                    }
                                }
                            }
                            ContactInfo.save({},a, function(result){
                                $scope.solved++;
                                if($scope.solved==$scope.length) df.resolve($scope.solved);
                            }, function(result){
                                df.reject(result.message);
                            })
                        }
                        $scope.submitImport=function() {
                            if (!confirm("确定要导入这"+$scope.length+"位联系人么")){ngDialog.closeAll();return;}
                            for (var i in $scope.body){
                                if ($scope.check[i]==1) $scope.uploadDate($scope.body[i]);
                            }
                            pm.then(function(data){
                                if($rootScope.toState.name=="contacthint")  $scope.loadAll();
                                alert("成功导入"+data+"个联系人");
                                $scope.loadAll();
                            },function(reason){
                                alert("导入失败:"+reason)
                            })
                            ngDialog.closeAll();
                        }
                    }]
                })
            })
        }
        $scope.upExcel = function (file) {
            if(!file)return;
            var reader = new FileReader();
            var name = file.name;
            reader.onload = function (e) {
                var data = e.target.result;

                var workbook = XLSX.read(data, {type: 'binary'});
                var array=sheet_to_data(workbook);
                /* DO SOMETHING WITH workbook HERE */
            };
            reader.readAsBinaryString(file);
        };
})




.controller('ContactHintController',function($scope,ContactInfo,$rootScope,$state,$timeout,DateUtils,$filter,Upload,Excel,$q,ngDialog){
    $scope.clear();
})

function showOrInput(n,option){
    //alert("wzh");
    var show=document.getElementById("contactDetail"+n+"Message");
    var inputtd=document.getElementById("contactDetail"+n+"Inputtd");
    var input=document.getElementById("contactDetail"+n+"Input");
    show.style.display=(option==0)?"none":"block";
    inputtd.style.display=(option==1)?"none":"block";
    if (option==0) input.focus();
}

